<?php
namespace app\kaoping\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\View;
class Wxpay extends First{
//在类初始化方法中，引入相关类库
    public function initialize() {
        vendor('WxPayPubHelper.WxPayPubHelper');
    }
    // 公众号支付
    public function index(){
        
        $oid=session('ordernum');
        $jsApi = new \JsApi_pub();      
        $wxpayconf=new \WxPayConf_pub();
        //=========步骤1：网页授权获取用户openid============
        if (!isset($_GET['code'])){            
           //触发微信返回code码
            $url = $jsApi->createOauthUrlForCode($wxpayconf::JS_API_CALL_URL);dump($url);die;
            Header("Location: $url");
        }else{
            //获取code码，以获取openid
            $code = $_GET['code'];dump($code);die;
            $jsApi->setCode($code);
            $openid = $jsApi->getOpenId();
        }
        dump($openid);die;
        //=========步骤2：使用统一支付接口，获取prepay_id============
        $unifiedOrder = new \UnifiedOrder_pub();
        //设置统一支付接口参数
        $unifiedOrder->setParameter("openid",$openid);//openid
        $unifiedOrder->setParameter("body","");//商品描述
        $unifiedOrder->setParameter("out_trade_no","wdzx".date('YmdHis').rand(1000,9999));//商户订单号 session('oid');
        $unifiedOrder->setParameter("total_fee",1);//总金额0.99*100
        $unifiedOrder->setParameter("notify_url",$wxpayconf::NOTIFY_URL);//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);
        $jsApiParameters = $jsApi->getParameters();

        //$this->assign("data",$info);
        $this->assign("jsApiParameters",$jsApiParameters);
        //return $this->fetch('recharge');
    }

    // 接收返回
    public function notify_url(){
        /**
            * 通用通知接口demo
            * 支付完成后，微信会把相关支付和用户信息发送到商户设定的通知URL， 商户接收回调信息后，根据需要设定相应的处理流程。 这里举例使用log文件形式记录回调信息。
        */
        //include_once("/public/log_.php");
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        //echo $returnXml;
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        //以log文件形式记录回调信息
        //$log_ = new Log_();
        //$log_name="/public/notify_url.log";//log文件路径
        //$log_->log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");
        $parameter = $notify->xmlToArray($xml);
        if($notify->checkSign() == TRUE){
            if ($notify->data["return_code"] == "FAIL") {
                echo 'error';// $log_->log_result($log_name,"【通信出错】:\n".$xml."\n");
            }elseif($notify->data["result_code"] == "FAIL"){
                echo 'error';//$log_->log_result($log_name,"【业务出错】:\n".$xml."\n");
            }else{
                echo 'success';
                /*if ($this->process($parameter)) {
                    echo 'success';//处理成功后输出success，微信就不会再下发请求了
                }else {                    
                    echo 'error';//没有处理成功，微信会间隔的发送请求
                }*/
            }
        }
    }

    // 调用退款接口
    public function refund(){
        //输入需退款的订单号
        if (!isset($_POST["out_trade_no"]) || !isset($_POST["refund_fee"])){
            $out_trade_no = " ";
            $refund_fee = "1";
        }else{
            $out_trade_no = $_POST["out_trade_no"];
            $refund_fee = $_POST["refund_fee"]*100;
            //商户退款单号，商户自定义，此处仅作举例
            $out_refund_no = 'tk_'."$out_trade_no";
            //总金额需与订单号out_trade_no对应，demo中的所有订单的总金额为1分
            $total_fee = "$refund_fee";
            
            //使用退款接口
            $refund = new \Refund_pub();
            //设置必填参数
            //appid已填,商户无需重复填写
            //mch_id已填,商户无需重复填写
            //noncestr已填,商户无需重复填写
            //sign已填,商户无需重复填写
            $refund->setParameter("out_trade_no","$out_trade_no");//商户订单号
            $refund->setParameter("out_refund_no","$out_refund_no");//商户退款单号
            $refund->setParameter("total_fee","$total_fee");//总金额
            $refund->setParameter("refund_fee","$refund_fee");//退款金额
            $refund->setParameter("op_user_id",WxPayConf_pub::MCHID);//操作员
            //非必填参数，商户可根据实际情况选填
            //$refund->setParameter("sub_mch_id","XXXX");//子商户号 
            //$refund->setParameter("device_info","XXXX");//设备号 
            //$refund->setParameter("transaction_id","XXXX");//微信订单号
            
            //调用结果
            $refundResult = $refund->getResult();
            
            //商户根据实际情况设置相应的处理流程,此处仅作举例
            if ($refundResult["return_code"] == "FAIL") {
                echo "通信出错：".$refundResult['return_msg']."<br>";
            }else{
                if($refundResult['result_code'] == "SUCCESS"){
                    // 改变订单状态
                    $orderid = $_POST['orderid'];
                    $order = M('Order');
                    $bzy['pay'] = 2;
                    $order->where('id='.$orderid)->save($bzy);
                    //echo $order->getlastsql();exit();
                    //echo "<meta charset=\"UTF-8\"><script>alert('退款成功！');window.location.href='".."';</script>";
                    $this -> redirect('Index/buylist',NULL,2,'退款成功！');
                }else{
                    echo "业务结果：".$refundResult['result_code']."<br>";
                    echo "错误代码：".$refundResult['err_code']."<br>";
                    echo "错误代码描述：".$refundResult['err_code_des']."<br>";
                }
                /*echo "业务结果：".$refundResult['result_code']."<br>";
                echo "错误代码：".$refundResult['err_code']."<br>";
                echo "错误代码描述：".$refundResult['err_code_des']."<br>";
                echo "公众账号ID：".$refundResult['appid']."<br>";
                echo "商户号：".$refundResult['mch_id']."<br>";
                echo "子商户号：".$refundResult['sub_mch_id']."<br>";
                echo "设备号：".$refundResult['device_info']."<br>";
                echo "签名：".$refundResult['sign']."<br>";
                echo "微信订单号：".$refundResult['transaction_id']."<br>";
                echo "商户订单号：".$refundResult['out_trade_no']."<br>";
                echo "商户退款单号：".$refundResult['out_refund_no']."<br>";
                echo "微信退款单号：".$refundResult['refund_idrefund_id']."<br>";
                //echo "退款渠道：".$refundResult['refund_channel']."<br>";
                echo "退款金额：".$refundResult['refund_fee']."<br>";
                echo "现金券退款金额：".$refundResult['coupon_refund_fee']."<br>";*/
            }
        }
    }

    //微信扫码支付
    function nativepay(){
        $oid=session('ordernum');
        $info=db('pici')->where('ordernum',$oid)->field('id,real_money,ordernum')->find();//dump($info);die;
        $u = new \UnifiedOrder_pub();
        $wxpayconf=new \WxPayConf_pub();
        $notify = new \JsApi_pub();

        $u->setParameter("body","学员报名费用");//商品描述
        $u->setParameter("out_trade_no",$info['ordernum']);//商户订单号 session('oid');
        $u->setParameter("total_fee",$info['real_money']*100);//总金额0.99*100		
        $u->setParameter("notify_url",$wxpayconf::NOTIFY_URL);//通知地址
        $u->setParameter("trade_type","NATIVE");//交易类型

        $unifiedOrderResult = $u->getResult();//dump($unifiedOrderResult);
        if ($unifiedOrderResult["return_code"] == "FAIL"){
            //商户自行增加处理流程
            echo "通信出错：".$unifiedOrderResult['return_msg']."<br>";
        }elseif($unifiedOrderResult["result_code"] == "FAIL"){
            //商户自行增加处理流程
            echo "错误代码：".$unifiedOrderResult['err_code']."<br>";
            echo "错误代码描述：".$unifiedOrderResult['err_code_des']."<br>";//dump($unifiedOrderResult);
        }elseif($unifiedOrderResult["code_url"] != NULL){
            $code_url = $unifiedOrderResult["code_url"];//从统一支付接口获取到code_url
            return view('',['out_trade_no'=>$info['ordernum'],'code_url'=>$code_url]);
        }
    }

    //查询订单
    public function orderQuery(){
         //out_trade_no='+$('out_trade_no').value,
        //退款的订单号
        if (!isset($_POST["out_trade_no"])){
            $out_trade_no = " ";
        }else{
            $out_trade_no = $_POST["out_trade_no"];
            
            $orderQuery = new \OrderQuery_pub();//使用订单查询接口
            //appid已填,商户无需重复填写 || mch_id已填,商户无需重复填写 || noncestr已填,商户无需重复填写 || sign已填,商户无需重复填写
            $orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号 
            //非必填参数，商户可根据实际情况选填 //$orderQuery->setParameter("sub_mch_id","XXXX");子商户号   //$orderQuery->setParameter("transaction_id","XXXX");微信订单号
            
            //获取订单查询结果
            $orderQueryResult = $orderQuery->getResult();
            //return json($orderQueryResult);
            //商户根据实际情况设置相应的处理流程,此处仅作举例
            if ($orderQueryResult["return_code"] == "FAIL") {
                $this->error($out_trade_no);
            }elseif($orderQueryResult["result_code"] == "FAIL"){
                //$this->ajaxReturn('','支付失败！',0);
                $this->error($out_trade_no);
            }else{
                switch ($orderQueryResult["trade_state"]){
                    case 'SUCCESS': 
                        db('pici')->where('ordernum="'.$out_trade_no.'"')->setfield('pay_state',1);
                        return json(['code'=>200,'msg'=>'支付成功']);
                        break;
                    case 'REFUND':
                        return json(['code'=>400,'msg'=>'转入退款 ']);
                        break;
                    case 'NOTPAY':
                        return json(['code'=>400,'msg'=>'未支付']);
                        break;
                    case 'CLOSED':
                        return json(['code'=>400,'msg'=>'已关闭']);
                        break;
                    case 'REVOKED':
                        return json(['code'=>400,'msg'=>'已撤销（付款码支付）']);
                        break;
                    case 'USERPAYING':
                        return json(['code'=>400,'msg'=>'用户支付中（付款码支付）']);
                        break;
                    case 'PAYERROR':
                        return json(['code'=>400,'msg'=>'支付失败']);
                        break;
                    default:
                        return json(['code'=>400,'msg'=>'支付失败']);
                        break;
                }
            }  
        }
    }
}